package logic

import (
	"context"
	"xialou_platform/app/errorx"
	"xialou_platform/services/system/model"

	"xialou_platform/services/system/rpc/internal/svc"
	"xialou_platform/services/system/rpc/systemClient"

	"github.com/zeromicro/go-zero/core/logx"
)

type SysUserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSysUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SysUserAddLogic {
	return &SysUserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SysUserAddLogic) SysUserAdd(in *systemClient.SysUser) (*systemClient.EmptyBody, error) {
	_, err := l.svcCtx.SysUserModel.FindOneByName(l.ctx, in.Name)
	if err != nil {
		if err == model.ErrNotFound {
			_, err = l.svcCtx.SysUserModel.Insert(l.ctx, &model.SysUser{
				Id:       l.svcCtx.Flake.Generate().Int64(),
				DeptId:   in.DeptId,
				Avatar:   in.Avatar,
				Name:     in.Name,
				Password: in.Password,
				Salt:     in.Salt,
				Gender:   in.Gender,
				Email:    in.Email,
				Phone:    in.Phone,
				Status:   0,
				CreateBy: in.CreateBy,
				UpdateBy: in.UpdateBy,
				DelFlag:  false,
				Role:     in.Role,
			})
			if err != nil {
				return nil, errorx.NewReasonError("网络出小差了，请重试刷新再试。", err.Error())
			}
			return &systemClient.EmptyBody{}, nil
		}
		return nil, errorx.NewReasonError("网络出小差了，请重试刷新再试。", err.Error())
	}

	return &systemClient.EmptyBody{}, errorx.NewDefaultError("该用户名已存在。")
}
